package com.basic.technology.study.introduction.thread.juc;

import java.util.concurrent.atomic.AtomicInteger;

public class Cas {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        // 模拟多线程并发自增
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int currentValue = counter.get();
                int newValue = currentValue + 1;

                // CAS操作：如果当前值等于预期值(currentValue)，则更新为新值(newValue)
                if (counter.compareAndSet(currentValue, newValue)) {
                    System.out.println("Incremented value: " + counter.get());
                } else {
                    System.out.println("CAS operation failed");
                }
            }).start();
        }
    }
}
